<template>
  <div class="index-container pb-16">
    <section class="bg-linear"
      id="linear">
      <div class="max-w-8xl mx-auto px-4 py-8 sm:px-6 lg:px-4">
        <div class="breadcrumbs space-x-2 text-base max-w-7xl mx-auto flex flex-wrap items-center mb-6">
          <common-link path="/"
            class="text-gray-1000 hover:text-purple-1200 go-home">
            {{$t('home')}}
          </common-link>
          <svg-icon className="text-gray-1800 text-mini text-slate-400 mx-3"
            iconName='right_outlined'></svg-icon>
          <span class="text-gray-1400 text-base">
            {{$t('favourites')}}
          </span>
        </div>

        <h1 class="title text-center text-gray-1000 break-words font-semibold">{{$t('toolsFavoritesTitle')}}</h1>

        <div class="mb-3 mt-10 max-w-5xl mx-auto md:px-4">
          <!-- <category-list class="mb-3"
            :categories-list="categoriesList"></category-list> -->
          <common-search></common-search>
        </div>
      </div>
    </section>

    <!-- <section class="max-w-8xl mx-auto px-4 sm:mt-1 sm:px-6 lg:px-4">
      <div class="max-w-5xl mx-auto md:px-4">
        <div class="sort flex sm:items-center sm:justify-between flex-wrap">
          <div class="flex sm:items-center gap-x-3 gap-y-5 sm:mr-5 mt-5 flex-wrap">
           <common-select v-for="(item,key) in attributesList"
              :key="item.handle"
              :targetObj="item"
              :attributesList="attributesList"
              :hasBorder="false"
              selectType="attributes"></common-select>
          </div>
          <div class="mt-5">
            <common-sort :targetObj="sortOptions"
              :hasBorder="false"
              selectType="sort"></common-sort>
          </div>
        </div>
      </div>
    </section> -->

    <section class="max-w-8xl mx-auto px-4 mt-6">
      <div class="tool-list grid gap-5 sm:grid-cols-3"
        v-if="toolsList && toolsList.length>0">
        <tools v-for="(item, key) in toolsList"
          :key="item.handle+'-'+key"
          :toolsData="item"></tools>
      </div>
      <div class="w-2/4 mx-auto mt-16 text-center"
        v-if="toolsList && toolsList.length>0">
        <el-button type="text"
          v-if="toolsList && toolsList.length>0 && next_page_url"
          class="cursor-default">
          <img src="@/static/images/loading.png"
            class="loading"
            alt=""
            srcset="">
        </el-button>

        <el-divider v-else>
          <el-button type="text"
            class="cursor-default"
            :loading="loading">{{ $t('end') }}</el-button>
        </el-divider>
      </div>
      <el-empty v-else
        :description="$t('noData')"></el-empty>
    </section>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
export default {
  name: 'Favorites',
  head() {
    return {
      htmlAttrs: {
        lang: this.locale,
      },
      meta: [
        {
          hid: 'description',
          name: 'description',
          content: this.description,
        },
        {
          hid: 'og:description',
          name: 'og:description',
          content: this.description,
        },
        {
          hid: 'og:url',
          name: 'og:url',
          content: this.canonicalLink,
        },
      ],
      link: [
        {
          rel: 'canonical',
          href: this.canonicalLink,
        },
      ],
    }
  },
  async asyncData({ app, route, params, query, $axiosApi, error, store }) {
    let pageDesc = app.$cookies.get('pageDesc')
    try {
      let req = JSON.parse(
        JSON.stringify({
          ...query,
          order_by: query.sort ? query.sort : null,
          page: 1,
          per_page: 30,
        })
      )
      if (query.sort) {
        req.order_by = query.sort
        delete req.sort
      }

      let [favoritesRes, langRes] = await Promise.all([
        await $axiosApi.getFavorites({
          ...req,
          page: 1,
          per_page: 30,
        }),
        await $axiosApi.getLanguagesMul(),
      ])

      let res = {}

      if (favoritesRes.code === 200) {
        res.toolsList =
          favoritesRes.data.data && favoritesRes.data.data.length > 0
            ? favoritesRes.data.data
            : []
        res.total = favoritesRes.data.total
        res.page = favoritesRes.data.current_page
          ? favoritesRes.data.current_page
          : 1
        res.per_page = favoritesRes.data.per_page
          ? favoritesRes.data.per_page
          : 20
        res.next_page_url = favoritesRes.data.next_page_url
          ? favoritesRes.data.next_page_url
          : null
      } else {
        if (favoritesRes && favoritesRes.code && favoritesRes.code === 404) {
          error({ statusCode: 404 })
        } else if (
          !(favoritesRes && favoritesRes.code && favoritesRes.code === 401)
        ) {
          error({
            message:
              'There is a problem with the network. Please refresh and try again later',
            statusCode: favoritesRes.code,
          })
        }
      }

      let description
      let curLocale = store.state.locale
      if (
        langRes.code === 200 &&
        langRes.data &&
        langRes.data.languages &&
        langRes.data.languages.description &&
        langRes.data.languages.description.length > 0 &&
        langRes.data.languages.description[0].content &&
        (langRes.data.languages.description[0].content[curLocale] ||
          langRes.data.languages.description[0].content.default)
      ) {
        if (langRes.data.languages.description[0].content[curLocale]) {
          description = langRes.data.languages.description[0].content[curLocale]
        } else {
          description = langRes.data.languages.description[0].content.default
        }

        app.$cookies.set('pageDesc', description, {
          maxAge: 60 * 60 * 24 * 7,
          path: '/',
        })
      } else if (pageDesc) {
        description = pageDesc
      }

      return {
        ...query,
        ...res,
        description,
      }
    } catch (err) {
      console.log(err)
    }
  },
  computed: {
    ...mapState({
      locale: (state) => state.locale,
    }),
  },
  watch: {
    $route: {
      handler(route) {
        if (route.name === this.$route.name) {
          this.getList(1)
        }
      },
      deep: true,
      immediate: true,
    },
  },
  data() {
    return {
      canonicalLink: `https://www.toolify.ai${this.$route.fullPath}`,
      toolsList: [],
      page: 1,
      per_page: 30,
      next_page_url: null,
      keyword: null,
      errorImage: require('@/static/images/default.webp'),
      loading: false,
      total: 0,

      attributesList: [],
      categoriesList: [],

      sortOptions: {
        isShowOptions: false,
        options: [
          { label: 'sortByCreatedAt', val: 'created_at' },
          {
            label: 'sortByMonthVisitedCount',
            val: 'month_visited_count',
          },
        ],
      },
      description: null,
    }
  },
  mounted() {
    window.addEventListener('scroll', this.onSroll)

    if (
      this.$route.query.keyword &&
      this.$route.query.keyword !== '' &&
      this.$route.query.keyword !== null &&
      document.getElementById('search')
    ) {
      this.keyword = this.$route.query.keyword
    }
  },
  methods: {
    ...mapMutations(['SET_RetrackExposure']),
    onSroll() {
      var scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop
      //变量windowHeight是可视区的高度
      var windowHeight =
        document.documentElement.clientHeight || document.body.clientHeight
      //变量scrollHeight是滚动条的总高度
      var scrollHeight =
        document.documentElement.scrollHeight || document.body.scrollHeight

      const footerHeight = document.querySelector('footer').offsetHeight

      //滚动条到底部的条件
      if (scrollTop + windowHeight + 1200 > scrollHeight - footerHeight) {
        if (this.next_page_url && !this.loading) {
          this.getList(this.page + 1)
        }
      }
    },
    async getList(page) {
      this.loading = true
      try {
        let req = JSON.parse(
          JSON.stringify({
            ...this.$route.query,
            order_by: this.$route.query.sort ? this.$route.query.sort : null,
            page: page,
            per_page: 30,
          })
        )
        if (this.$route.query.sort) {
          delete req.sort
        } else {
          delete req.order_by
        }

        const res = await this.$axiosApi.getFavorites(req)

        this.loading = false

        if (res.code === 200) {
          if (page === 1) {
            this.toolsList = res.data.data
          } else {
            this.toolsList = this.toolsList.concat(res.data.data)
          }
          this.page = res.data.current_page ? res.data.current_page : 1
          this.per_page = res.data.per_page ? res.data.per_page : 20
          this.next_page_url = res.data.next_page_url
            ? res.data.next_page_url
            : null
          this.SET_RetrackExposure(Date.now())
        } /* else if (res.code === 401) {
          this.$router.push({
            name: this.locale === 'en' ? 'login' : 'lang-login',
          })
        } else {
          this.$message.error(res.message)
        } */
      } catch (error) {
        this.loading = false
      }
    },
    updateData(handle) {
      let cIndex = this.toolsList.findIndex((item) => {
        return item.handle === handle
      })
      if (cIndex >= 0) {
        this.toolsList.splice(cIndex, 1)
      }
    },
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.onSroll, false)
  },
}
</script>
<style lang='scss' scoped>
.index-container {
  .title {
    font-size: 62px;
    line-height: 76px;
  }
  .desc {
    font-size: 22px;
    line-height: 28px;
  }

  .label {
    font-size: 0;
  }
  ::v-deep .el-divider__text {
    background-color: #fff;
  }
}
</style>
